<template>
  <el-row
    type="flex"
    justify="space-between"
    align="middle"
    style="height: 40px; width: 100%"
    class="custom-tree-node"
  >
    <!-- 一列 -->
    <el-col :span="18">
      <i v-if="root" class="el-icon-s-home" />
      <span>{{ nodeData.name }}</span>
    </el-col>
    <!-- 另一列 -->
    <el-col :span="6">
      <el-row type="flex" justify="end">
        <el-col class="info">{{ nodeData.manager }}</el-col>
        <el-col class="info">
          <el-dropdown @command="handleCommand">
            <span class="el-dropdown-link" @click.stop>
              操作
              <i class="el-icon-arrow-down el-icon--right" />
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="add">添加子部门</el-dropdown-item>
                <el-dropdown-item v-if="!root" command="edit">查看部门</el-dropdown-item>
                <el-dropdown-item v-if="!root" command="del">删除部门</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </el-col>
      </el-row>
    </el-col>
  </el-row>
</template>

<script>
import { delDepartment } from '@/api/departments'
export default {
  props: {
    nodeData: {
      type: Object,
      required: true
    },
    root: {
      type: Boolean,
      default: false
    }
  },
  methods: {
    // 处理下拉菜单各项点击事件
    handleCommand(command) {
      if (command === 'add') this.add()
      if (command === 'edit') this.edit()
      if (command === 'del') this.del()
    },
    // 添加子部门
    add() {
      this.$emit('add')
    },
    // 查看部门
    edit() {
      this.$emit('edit')
    },
    // 删除部门
    async del() {
      try {
        await this.$confirm('此操作将删除该部门, 是否继续?', '提示', { type: 'warning' })
      } catch {
        return
      }
      // 点击确定后走到这里
      await delDepartment(this.nodeData.id)
      // 成功删除后往下走, 失败后拦截器统一提示
      this.$message.success('删除成功')
      // 通知父组件更新
      this.$emit('updateDepartments')
    }
  }
}
</script>

<style scoped lang="scss">
.info {
  width: 80px;
  padding-left: 20px;
  // 单行溢出
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>
